import React, { useState, useEffect, useRef } from "react";
import { Image, Button, Popconfirm, message, notification } from "antd";
import { ProTable, ProCard } from "@ant-design/pro-components";

import ProForm, { ModalForm } from "@ant-design/pro-form";
import { fetchBooksList } from "@/api/package";
import { BOOK_NUM } from "@/const";
import _ from "lodash";

const columns = [
  {
    title: "书本名称",
    dataIndex: "title",
    width: 400,
  },
  {
    title: "封面",
    dataIndex: "picture",
    width: 150,
    search: false,
    render: (_, record) => {
      return <Image width={80} height={80} src={record.picture} />;
    },
  },
  {
    title: "作者",
    dataIndex: "author",
    width: 150,
    search: false,
  },
  {
    title: "出版社",
    dataIndex: "publishingHouse",
    width: 150,
    search: false,
  },
];

const MyModal = ({ cycle, selectedIds = [], value = [], onChange }) => {
  const actionRef = useRef();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  return (
    <ModalForm
      title={`添加第${cycle}期书本`}
      trigger={<Button type="primary">添加书本</Button>}
      width={1200}
      layout="horizontal"
      modalProps={{
        destroyOnClose: true,
      }}
      onVisibleChange={() => {
        setSelectedRows([]);
        setSelectedRowKeys([]);
      }}
      onFinish={() => {
        // 取当前选择的和每一期选择的进行取交集
        const repeatArr = _.intersectionWith(
          selectedRows,
          selectedIds.length
            ? selectedIds.map((item) => {
                return {
                  id: item,
                };
              })
            : [],
          (objValue, othValue) => {
            return objValue.id === othValue.id;
          }
        );
        // 如果存在重复的就提示
        if (repeatArr.length) {
          let str = "";
          repeatArr.forEach((item) => {
            str += `《${item.title}》 `;
          });
          notification.error({
            message: "提示",
            description: `已添加的书本：${str} 不能重复添加`,
          });
          return;
        }
        // 将新选的和老的一起返回
        onChange([...selectedRows, ...value]);
        return true;
      }}
    >
      <ProTable
        tableStyle={{
          height: 500,
          overflowY: "auto",
        }}
        actionRef={actionRef}
        rowKey="id"
        options={false}
        columns={columns}
        request={fetchBooksList}
        // request={async (params) => {
        //   console.log("params===", params);
        //   const res = await fetchBooksList(params);
        //   const data = res.data?.filter(
        //     (item) => !selectedIds.includes(item.id)
        //   );
        //   console.log("selectedIds===", selectedIds, data);

        //   return {
        //     data,
        //     success: true,
        //   };
        // }}
        // pagination={false}
        rowSelection={{
          selectedRowKeys,
          onChange: (newSelectedRowKeys, newSelectedRows) => {
            setSelectedRowKeys(newSelectedRowKeys);
            setSelectedRows(newSelectedRows);
          },
          // getCheckboxProps: (record) => ({
          //   disabled: record.status === 2,
          // }),
          // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
        }}
      />
    </ModalForm>
  );
};
export default ({ cycle, selectedIds = [], value = [], onChange }) => {
  const colums2 = [
    ...columns,
    {
      title: "操作",
      dataIndex: "option",
      width: 200,
      render: (_, record) => {
        return (
          <Button
            danger
            type="primary"
            onClick={() => {
              const newValue = value.filter((item) => item.id !== record.id);
              onChange(newValue, record.id);
            }}
          >
            删除
          </Button>
        );
      },
    },
  ];
  return (
    <ProCard
      style={{ marginTop: 20 }}
      extra={
        <MyModal
          cycle={cycle}
          value={value}
          selectedIds={selectedIds}
          onChange={(books) => {
            onChange(
              books.map((item) => {
                return {
                  ...item,
                  booksId: item.booksId || item.id,
                };
              })
            );
          }}
        />
      }
    >
      <ProTable
        dataSource={value}
        rowKey="id"
        options={false}
        search={false}
        columns={colums2}
        pagination={false}
      />
    </ProCard>
  );
};
